package com.wcs.exam.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wcs.exam.common.constant.BaseConstant;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author wcs
 */
@Slf4j
public final class JwtUtil {

    /**
     * 1个月
     */
    public static final Long DATE = 30 * 24 * 3600 * 1000L;
    public final static String TYPE = "type";
    private static final String TOKEN_SECRET = "exam";
    private static final String ISSUER = "wcs";
    private static final String ADMIN = "admin";

    private JwtUtil() {
    }

    /**
     * @param userId 用户ID
     * @param date   有效时间
     * @return token
     */
    public static String create(Long userId, Long date) {
        return JWT.create().withIssuer(ISSUER).withClaim(BaseConstant.USER_ID, userId).withClaim(TYPE, ADMIN).withExpiresAt(new Date(System.currentTimeMillis() + date)).sign(Algorithm.HMAC256(TOKEN_SECRET));
    }

    /**
     * @param token 令牌
     * @return 解码的JWT
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer(ISSUER).build().verify(token);
    }

    /**
     * 获取用户ID
     *
     * @param decodedJWT 解码后JWT信息
     * @return 登录账号
     */
    public static Long getUserId(DecodedJWT decodedJWT) {
        return decodedJWT.getClaim(BaseConstant.USER_ID).asLong();
    }


}
